#!/bin/sh

if [ -e $(dirname "$0")/nsenter ]; then
    # with boot2docker, nsenter is not in the PATH but it is in the same folder
    NSENTER=$(dirname "$0")/nsenter
else
    NSENTER=nsenter
fi

if [ -e $(dirname "$0")/importenv ]; then
    # with boot2docker, importenv is not in the PATH but it is in the same folder
    IMPORTENV=$(dirname "$0")/importenv
else
    IMPORTENV=importenv
fi

if [ -z "$1" ]; then
    echo "Usage: `basename "$0"` CONTAINER [COMMAND [ARG]...]"
    echo ""
    echo "Enters the Docker CONTAINER and executes the specified COMMAND."
    echo "If COMMAND is not specified, runs an interactive shell in CONTAINER."
    exit
fi

PID=$(docker inspect --format "{{.State.Pid}}" "$1")
[ -z "$PID" ] && exit 1
shift

if [ "$(id -u)" -ne "0" ]; then
    which sudo > /dev/null
    if [ "$?" -eq "0" ]; then
      LAZY_SUDO="sudo "
    else
      echo "Warning: Cannot find sudo; Invoking nsenter as the user $USER." >&2
    fi
fi

ENVIRON="/proc/$PID/environ"

# Prepare nsenter flags
OPTS="--target $PID --mount --uts --ipc --net --pid --"

# env is to clear all host environment variables and set then anew
if [ $# -lt 1 ]; then
    # No arguments, default to `su` which executes the default login shell
    $LAZY_SUDO "$IMPORTENV" "$ENVIRON" "$NSENTER" $OPTS su -m root
else
    # Has command
    # "$@" is magic in bash, and needs to be in the invocation
    $LAZY_SUDO "$IMPORTENV" "$ENVIRON" "$NSENTER" $OPTS "$@"
fi
